package com.example.bankingsystemandroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.bankingsystemandroid.Holder.InfoHolder;
import com.example.bankingsystemandroid.utils.EncryptionUtil;
import com.example.bankingsystemandroid.utils.PropertiesConfig;
import com.example.bankingsystemandroid.utils.PropertyManager;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChangePasswordFragment extends Fragment {

	public ChangePasswordFragment() {
	}

	EditText currentPasswordEditText;
	EditText newPasswordEditText;
	EditText confirmNewPasswordEditText;
	Button confirmButton;
	Button declineButton;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_change_password,
				container, false);
		currentPasswordEditText = (EditText) rootView
				.findViewById(R.id.currentPassword);
		newPasswordEditText = (EditText) rootView
				.findViewById(R.id.newPassword);
		confirmNewPasswordEditText = (EditText) rootView
				.findViewById(R.id.confirmNewPassword);
		confirmButton = (Button) rootView.findViewById(R.id.btnAccept);
		declineButton = (Button) rootView.findViewById(R.id.btnDecline);

		confirmButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final String currentPassword = currentPasswordEditText
						.getText().toString();
				final String newPassword = newPasswordEditText.getText()
						.toString();
				final String confirmPassword = confirmNewPasswordEditText
						.getText().toString();
				if (!isValidInput(currentPassword)) {
					currentPasswordEditText.setError("Enter your password");
				} else if (!isValidInput(newPassword)) {
					newPasswordEditText.setError("Enter a vaild new password");
				} else if (!isValidInput(confirmPassword)) {
					confirmNewPasswordEditText
							.setError("Re-type new password correctly");
				} else if (!isCorrectConfirmPassword(confirmPassword,
						newPassword)) {
					confirmNewPasswordEditText
							.setError("Re-type new password correctly");
				} else {
					// do change password
					try {
						ArrayList<NameValuePair> postParameters;
						postParameters = new ArrayList<NameValuePair>();
						postParameters.add(new BasicNameValuePair(
								"oldPassword",
								EncryptionUtil
										.generateMD5HashFromString(currentPassword)));
						postParameters.add(new BasicNameValuePair(
								"newPassword", EncryptionUtil
										.generateMD5HashFromString(newPassword)));

						ChangPasswordTask changPasswordTask = new ChangPasswordTask(
								getActivity());
						changPasswordTask.execute(postParameters);
					} catch (NoSuchAlgorithmException e) {
						e.printStackTrace();
					}
				}
			}
		});
		declineButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// confirm change password
			}
		});
		return rootView;
	}

	// validating input
	private boolean isValidInput(String input) {
		if (input != null && input.length() >= 5) {
			return true;
		}
		return false;
	}

	// validating validating confirm password
	private boolean isCorrectConfirmPassword(String confirmPassword,
			String newPassword) {
		if (confirmPassword.equals(newPassword)) {
			return true;
		}
		return false;
	}

	public class ChangPasswordTask extends
			AsyncTask<ArrayList<NameValuePair>, Void, String> {
		private Context context;

		public ChangPasswordTask(Context context) {
			super();
			this.context = context.getApplicationContext();
		}

		@Override
		protected String doInBackground(ArrayList<NameValuePair>... params) {
			/*
			 * Create the POST request
			 */
			HttpClient httpClient = new DefaultHttpClient();
			String serverIP = PropertiesConfig
					.getProperty(PropertyManager.SERVER_IP);
			String serverPort = PropertiesConfig
					.getProperty(PropertyManager.SERVER_PORT);
			HttpPost httpPost = new HttpPost("http://" + serverIP + ":"
					+ serverPort + "/bankingsystem/api/change-password");
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params[0]));
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}
			/*
			 * Execute the HTTP Request
			 */
			try {
				httpPost.addHeader("Cookie",
						"JSESSIONID=" + InfoHolder.getSessionId());

				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity respEntity = response.getEntity();
				if (respEntity != null) {
					try {
						String retSrc = EntityUtils.toString(respEntity);
						JSONObject result = new JSONObject(retSrc);
						String resultCode = result.getString("code");
						return resultCode;
					} catch (ParseException e) {
						e.printStackTrace();
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			} catch (ClientProtocolException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (IOException e) {
				// writing exception to log
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if ("SUCCESS".equals(result)) {
				InfoHolder.clearInfo();
				SharedPreferences pre = getActivity().getSharedPreferences(InfoHolder.PREFS_NAME,
						android.content.Context.MODE_PRIVATE );
				SharedPreferences.Editor editor = pre.edit();
				editor.clear();

				editor.putString("username", InfoHolder.getUsername());
				editor.putString("token", InfoHolder.getToken());
				editor.putString("password", InfoHolder.getPassword());

				editor.commit();
				getActivity().finish();
				context.startActivity(new Intent(context, LoginActivity.class)
						.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
			} else if ("INVALID_OLD_PASSWORD".equals(result)) {
				Toast.makeText(context, "Current password is invalid",
						Toast.LENGTH_SHORT).show();
			} else if ("INTERNAL_SERVER_ERROR".equals(result)) {
				Toast.makeText(context,
						"Internal server error! Please try again later!",
						Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(result);
		}

	}
}
